package pl.bristleback.scrumtable.actions;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
import org.jwebsocket.api.WebSocketConnector;
import org.jwebsocket.token.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import pl.bristleback.scrumtable.services.WidgetService;
import pl.bristleback.scrumtable.utils.SendMessageSupport;
import pl.bristleback.scrumtable.vo.Position;
import pl.bristleback.scrumtable.vo.Widget;
import pl.bristleback.server.bristle.actions.AnnotatedRemoteAction;
import pl.bristleback.server.bristle.actions.RemoteAction;
import pl.bristleback.server.bristle.token.Tokenize;
import pl.bristleback.server.bristle.token.Tokenizer;
import pl.bristleback.server.bristle.utils.BristleTokenFactory;

/**
 * //@todo class description
 * <p/>
 * Created on: 25.05.11 15:12 <br/>
 *
 * @author Paweł Machowski
 */
@AnnotatedRemoteAction(actionName = "addWidget")
@Controller
public class AddWidgetAction implements RemoteAction{
  private static Logger log = Logger.getLogger(AddWidgetAction.class.getName());

  private static final String NOTE_NAME_PROPERTY = "noteName";
  private static final String ID_PROPERTY = "id";
  private static final String WIDGET_ADDED_ACTION_NAME = "widgetAdded";

  @Autowired
  private SendMessageSupport messageSender;

  @Autowired
  private WidgetService widgetService;

//  @Tokenize(parameters = {"id", "noteName", "position"}, deepSearch = true)
  @Tokenize(parameters = {"widget"}, deepSearch = true)
  private Tokenizer tokenizer;

  @Override
  public void performAction(WebSocketConnector connector, Token token) {

    String newId = RandomStringUtils.randomAlphabetic(15);
    String noteName = token.getString(NOTE_NAME_PROPERTY);
    Position position = new Position();
    position.setHeight(120);
    position.setWidth(120);
    position.setTop(125);
    position.setLeft(60);
    Widget widget = new Widget(newId, noteName);
    widget.setPosition(position);

    widgetService.addWidget(widget);

    Token sendToken = BristleTokenFactory.createJsonToken(WIDGET_ADDED_ACTION_NAME);
    tokenizer.tokenize(sendToken, widget);

    messageSender.broadcastNotLogged(sendToken);

  }
}